<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
        <el-form-item label="离职日期" >
          <el-date-picker clearable
            v-model="queryParams.workDate"
            type="date"
            size="small"
            value-format="yyyy-MM-dd"
            placeholder="请选择离职日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请单编号">
          <el-input 
            v-model="queryParams.applyNo"
            placeholder="请输入申请单编号"
            clearable
            size="small"
            style="width: 150px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-button type="primary" size="mini" icon="el-icon-plus"  @click="handleAdd">创建部门用人申请</el-button>
      </el-row>
  
      <el-table v-loading="loading" :data="deployList">
        <el-table-column label="申请单编号" prop="applyNo" align="center" width="180">
          <template slot-scope="scope">
              <el-link type="primary" @click="handleView(scope.row)">{{scope.row.applyNo}}</el-link>
          </template>
        </el-table-column>
  
        
        <el-table-column label="申请部门" align="center" prop="applyUserDeptName" :show-overflow-tooltip="true" />
        <el-table-column label="到岗日期" align="center" prop="workDate" :show-overflow-tooltip="true"/>
        <el-table-column label="用人原因" align="center" prop="usePersonReason" :show-overflow-tooltip="true" >
        </el-table-column>
        <el-table-column label="岗位要求" align="center" prop="workRequire">
        </el-table-column>
        
        <el-table-column label="申请单状态" align="center" prop="status" >
          <template slot-scope="scope">
              <el-tag v-if="scope.row.status==0" type="info">草稿</el-tag>
              <el-tag v-if="scope.row.status==1" type="primary">待审批</el-tag>
              <el-tag v-if="scope.row.status==2" type="danger">审批驳回</el-tag>
              <el-tag v-if="scope.row.status==3" type="success">审批通过</el-tag>
              <el-tag v-if="scope.row.status==4" type="danger">撤销</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="当前审批人" align="center" prop="currApprovedBy" />
        <el-table-column label="提交人" align="center" prop="createBy" />
        <el-table-column label="提交时间" align="center" prop="createTime" :show-overflow-tooltip="true">
          <template slot-scope="scope">
              {{parseTime(scope.row.modifyTime)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" >
          <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="撤销申请" placement="top">
                  <el-button
                      size="mini"
                      circle type="warning"
                      icon="el-icon-refresh-left"
                      v-if="scope.row.status==1"
                      @click="cancelApply(scope.row)"
                  />
              </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <el-dialog title="创建部门用人申请" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
          <el-form :model="usePersonFormData" ref="usePersonFormData" :rules="rules" label-width="120px">
            <el-row>
                  <el-col :span="12">
                      <el-form-item label="申请人">
                          {{usePersonFormData.applyUser}}
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="申请部门" >
                        {{usePersonFormData.applyUserDeptName}}
                      </el-form-item>
                  </el-col>
              </el-row>
              <el-row>
                  <el-col :span="12">
                      <el-form-item label="到岗日期" prop="workDate">
                          <el-date-picker
                              :disabled="isView"
                              style="width:100%"
                              v-model="usePersonFormData.workDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择开始日期">
                          </el-date-picker>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="用人类型" prop="usePersonType">
                        <el-select v-model="usePersonFormData.usePersonType" style="width:100%" clearable :disabled="isView">
                            <el-option v-for="item in usePersonTypeOptions" :key="item.id" 
                                :value="item.dictValue" :label="item.dictLabel"></el-option>
                        </el-select>
                      </el-form-item>
                  </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                      <el-form-item label="岗位要求" prop="isReturnEquipment">
                          <el-input v-model="usePersonFormData.workRequire" clearable style="width:100%" :disabled="isView"></el-input>
                      </el-form-item>
                </el-col>
                <el-col :span="12">
                      <el-form-item label="岗位职责" prop="approvedDept">
                        <el-input v-model="usePersonFormData.workDuty" clearable style="width:100%" :disabled="isView"></el-input>
                      </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="用人原因" prop="usePersonReason">
                  <el-input v-model="usePersonFormData.usePersonReason" clearable type="textarea"  :disabled="isView"></el-input>
              </el-form-item>

              <el-form-item label="抄送人" prop="ccUsers">
                <el-tag v-for="item in ccUserList" :key="item.id" style="margin-left: 3px;">{{item.userName}}</el-tag>
                <el-button type="info" plain size="mini" icon="el-icon-plus" v-if="!isView" @click="handleUser">选择抄送人</el-button>
                <el-button type="info" plain size="mini" icon="el-icon-delete"  @click="clearUser" v-if="ccUserList.length>0 && !isView">清空抄送人</el-button>
              </el-form-item>
              <el-form-item label="上传附件" >
                <el-upload :disabled="isView"
                  class="upload-demo"
                  :action="upload.url"
                  :headers="headers"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  multiple
                  :limit="3"
                  :on-exceed="handleExceed"
                  :on-success="handleSuccess"
                  :file-list="fileList">
                  <el-button size="mini" plain v-if="!isView">点击上传</el-button>
                </el-upload>
              </el-form-item>
          </el-form>
          <div >
            <approvalHistory :processId="usePersonFormData.processId" v-if="usePersonFormData.processId && dialogVisible"></approvalHistory>
          </div>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm" v-if="!isView" :loading="submitLoading">提 交</el-button>
              <el-button @click="handleClose">取 消</el-button>
          </div>
      </el-dialog>
  
      <!-- <el-dialog title="文件预览" :visible.sync="previewDialogVisible" width="50%">
        <iframe id="iframeRef" ref="iframeRef" :src="iframeUrl" class="ifsty"></iframe>
      </el-dialog> -->
      <el-dialog :visible.sync="dialogVisibleUser" title="选择人员">
        <deptUser @getTaskUser="getCCuser" :multiple="true" v-if="dialogVisibleUser"></deptUser>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getToken } from "@/utils/auth";
  import {pageList,createUsePersonApply,cancelUsePersonApply} from "@/api/workflow/usePersonApply"
  import approvalHistory from '../../components/workflow/approvalHistory'
  import deptUser from '../../components/userSelect/deptUser.vue'
  import {getUserProfile} from "@/api/system/user"
  
  export default {
    name: "quitApply",
    components: {
      approvalHistory,
      deptUser
    },
    data() {
      return {
        // iframeUrl:null,
        props:{multiple: true},
        // 遮罩层
        loading: true,
        submitLoading:false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 参数表格数据
        deployList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 类型数据字典
        typeOptions: [],
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          paramName: undefined,
          paramKey: undefined,
          paramType: undefined
        },
        dialogVisible:false,
        dialogVisibleUser:false,
        usePersonFormData:{
  
        },
        rules:{
          workDate:[{ required: true, message: "请选择离职时间", trigger: "blur"}],
          usePersonType:[{ required: true, message: "请选择用人类型", trigger: "blur"}],
          usePersonReason:[{ required: true, message: "请填写用人原因", trigger: "blur"}],
          quitRemarks:[{ required: true, message: "请填写离职原因", trigger: "blur"}],
        },
        leaveTypeList:[],
        isView:false,
        deptOptions:[],
        fileList:[],
        upload:{
          url: process.env.VUE_APP_BASE_API + "/test/uploadImage",
        },
        previewDialogVisible:false,
        ccUserList:[],
        userInfo:null,
        usePersonTypeOptions:[]
      };
    },
    computed: {
      headers() {
        return {
          'Authorization': getToken()
        }
      }
    },
    created() {
        
        this.getList();
        this.getDicts("use_person_type").then(response => {
            this.usePersonTypeOptions = response.data;
        });

  
    },
    methods: {
        getUserInfo(){
            //用户信息
            getUserProfile().then(resp=>{
                this.userInfo = resp.data
                this.usePersonFormData.applyUser = resp.data.username
                this.usePersonFormData.applyUserDeptId = resp.data.deptId
                this.usePersonFormData.applyUserDeptName = resp.data.deptName
                this.$forceUpdate();
                console.log(this.usePersonFormData)
            })
        },
      handleUser(){
        this.dialogVisibleUser = true
      },
      clearUser(){
        this.ccUserList=[]
        this.leaveFormData.ccUsers=null
      },
      getCCuser(data,isClose){
        this.ccUserList = data
        if(data){
          let ccUser = []
          for(let i=0;i<data.length;i++){
            ccUser.push(data[i].userName)
          }
          this.usePersonFormData.ccUsers = ccUser.join(',')
        }
        this.dialogVisibleUser = isClose
      },
      preFile(fileName){
        window.open(process.env.VUE_APP_BASE_API + "/school/file/" +fileName)
      },
      
      /** 查询参数列表 */
      getList() {
        this.loading = true;
        pageList(this.queryParams).then(response => {
            this.deployList = response.data.list;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          paramName: undefined,
          paramKey: undefined,
          paramValue: undefined,
          paramType: "Y",
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.queryParams={
          pageNum: 1,
          pageSize: 10,
          workDate:null,
          applyNo:null
        }
        this.handleQuery();
      },
      resetForm(){
          this.usePersonFormData={
              workDate:undefined,
              isHandover:undefined,
              isReturnEquipment:undefined,
              quitRemarks:undefined
          }
      },
      handleView(row){
          this.fileList = []
          this.isView = true
          this.usePersonFormData = row
          if(row.fileList){
            const sFile = row.fileList.split(',')
            for(let i=0;i<sFile.length;i++){
                this.fileList.push({
                url:sFile[i],
                name:row.fileResourceNames.split(',')[i]
                })
    
            }
          }
          
          this.ccUserList = []
          if(row.ccUsers){
            let ccUsers = row.ccUsers.split(',')
            this.ccUserList = ccUsers.map(item =>{
                return {userName:item}
            })
          }
          
          this.dialogVisible = true
      },
      handleClose(done){
          this.dialogVisible = false
      },
      handleAdd(){
          this.resetForm()
          //初始查询用户信息
          this.getUserInfo()
          this.dialogVisible = true
          this.isView = false
          this.fileList =[]
          this.clearUser()
          
      },
      submitForm(){
          console.log(this.usePersonFormData)
          console.log(this.fileList)
          this.getFormFileList()
          console.log(this.usePersonFormData)
          this.$refs["usePersonFormData"].validate(valid => {
              if(valid){
                  this.submitLoading=true
                  createUsePersonApply(this.usePersonFormData).then(resp=>{
                      this.submitLoading = false
                      this.$message({ message: '提交成功', type: 'success' });
                      this.dialogVisible = false
                      this.getList()
                  })
              }
          })
      },
      cancelApply(row){
          this.$confirm('取消要撤销请假申请吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
              const applyData = {
                  processInstanceId: row.processId
              }
              this.loading = true
              cancelUsePersonApply(applyData).then(resp=>{
                  this.$message({ type: 'success', message: '撤销成功!'});
                  this.getList()
              })
            
          })
      },
      changeDept(item){
        console.log(item)
        if(item.length>0){
          let depts = []
          for(let i=0;i<item.length;i++){
            depts.push(item[i].join(','))
          }
          this.usePersonFormData.approvedDept = depts.join(';')
        }
        
      },
      handleRemove(file, fileList) {
        //删除文件是触发
          console.log(file, fileList);
          this.fileList = fileList
  
      },
      handlePreview(file) {
        //点击文件是触发预览
        console.log(file);
        this.preFile(file.url)
        // window.open('https://view.officeapps.live.com/op/view.aspx?src=' + );
      },
      handleExceed(files, fileList) {
        //文件上传数量超过执行数量
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        //删除文件之前触发
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleSuccess(response, file, fileList){
        //文件上传成功时触发
        console.log("response",response,file,fileList)
        this.getFileList(fileList)
      },
      getFileList(allFileList){
        if(!allFileList) {
          return
        } 
        for(let i=0;i<allFileList.length;i++){
          if(allFileList[i].response){
            this.fileList.push({
            name:allFileList[i].name,
            url:allFileList[i].response.result
          })
          }
          
        }
      },
      getFormFileList(){
        if(this.fileList){
          let names = []
          let urls = []
          for(let i=0;i<this.fileList.length;i++){
             names.push(this.fileList[i].name)
             urls.push(this.fileList[i].url)
          }
          this.usePersonFormData.fileResourceNames = names.join(',')
          this.usePersonFormData.fileList = urls.join(',')
        }
      }
    }
  };
  </script>
  
  <style>
  .ifsty{
    width: 100%;
      height: 500px;
      border: 0px;
  }
  .el-upload {
    display: flex;
}
  </style>